package models

import (
	"time"
	"github.com/astaxie/beego/orm"
	"log"
)

type Devices struct {
	Id               int
	DeviceName       string    `ht:"list;search;name(设备名称)"  valid:"Required"`
	DevicePass       string    `ht:"name(设备密码)"`
	DeviceSN         string    `ht:"hide;name(SN码)"`
	PointModule      int       `ht:"list;name(抽奖模板编码)"`
	DeviceType       int       `ht:"name(设备类型);subclass([{\"Num\":1,\"Name\":\"设备端抽奖\"},{\"Num\":2,\"Name\":\"用户端抽奖\"}])"`
	Coupons          int       `ht:"hide;name(抽奖模板优惠券编码)"`
	DeviceCreateTime time.Time `ht:"list;name(创建时间)"`
	DeviceUpdateTime time.Time `ht:"name(更新时间)"`

	DeviceStatus   int    `orm:"default(0)" ht:"list;name(设备状态);status([{\"Num\":0,\"Name\":\"初始化\"},{\"Num\":1,\"Name\":\"正常运行\"},{\"Num\":2,\"Name\":\"维修检测\"},{\"Num\":3,\"Name\":\"故障\"}])"`
	DeviceTopic    string `ht:"name(topic)"`
	DeviceAuthName string `ht:"name(authName)"`
	DeviceAuthPass string `ht:"name(authPass)"`

	DeviceBackGroundPic string `ht:"name(设备图片);type(pic)"`
	DevicePosition      int    `ht:"list;name(地点编号)"`
	User                int    `ht:"name(设备用户编号)"`
}

func init() {
	orm.RegisterModel(new(Devices))
}
func (*Devices) TableName() string {
	return "devices"
}

func (*Devices) FN_Id() string {
	return "Id"
}
func (*Devices) FN_DevicePass() string {
	return "DevicePass"
}
func (*Devices) FN_DeviceName() string {
	return "DeviceName"
}
func (*Devices) FN_DeviceType() string {
	return "DeviceType"
}
func (*Devices) FN_DeviceSN() string {
	return "DeviceSN"
}
func (*Devices) FN_PointModule() string {
	return "PointModule"
}
func (*Devices) FN_Coupons() string {
	return "Coupons"
}
func (*Devices) FN_DeviceCreateTime() string {
	return "DeviceCreateTime"
}
func (*Devices) FN_DeviceUpdateTime() string {
	return "DeviceUpdateTime"
}
func (*Devices) FN_DeviceStatus() string {
	return "DeviceStatus"
}
func (*Devices) FN_DeviceTopic() string {
	return "DeviceTopic"
}
func (*Devices) FN_DeviceAuthName() string {
	return "DeviceAuthName"
}
func (*Devices) FN_DeviceAuthPass() string {
	return "DeviceAuthPass"
}
func (*Devices) FN_DeviceBackGroundPic() string {
	return "DeviceBackGroundPic"
}
func (*Devices) FN_DevicePosition() string {
	return "DevicePosition"
}
func (*Devices) FN_User() string {
	return "User"
}

func DeviceGetInfo(device *Devices) error {
	o := orm.NewOrm()
	return o.Read(device)
}

func CheckDevicePass(Id int, pass string) bool {
	o := orm.NewOrm()
	device := Devices{Id: Id}
	o.Read(&device)
	if device.DevicePass == pass {
		return true
	}
	return false
}

func UpdateDeviceTime(Id int) {
	o := orm.NewOrm()
	m := Devices{Id: Id}
	_, err := o.QueryTable(m.TableName()).Filter(m.FN_Id(), Id).Update(orm.Params{
		m.FN_DeviceUpdateTime(): time.Now()})
	if err != nil {
		log.Printf("update time error when update Device:%d\r\n", Id)
	}
}
